﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VIB.Model;
using System.Net;
using System.IO;
using System.Windows;
using System.Web;
using System.Web.Script.Serialization;




namespace VIB
{
    class OpenLibrary
    {
        private class Publisher
        {
            public string name { get; set; }
        }

        private class Identifiers
        {
            public List<string> isbn_13 { get; set; }
            public List<string> openlibrary { get; set; }
            public List<string> isbn_10 { get; set; }
            public List<string> goodreads { get; set; }
            public List<string> librarything { get; set; }
        }

        private class Cover
        {
            public string small { get; set; }
            public string large { get; set; }
            public string medium { get; set; }
        }

        private class Author
        {
            public string url { get; set; }
            public string name { get; set; }
        }

        private class OpenLibraryBook
        {
            public List<Publisher> publishers { get; set; }
            public Identifiers identifiers { get; set; }
            public string weight { get; set; }
            public string title { get; set; }
            public string url { get; set; }
            public int number_of_pages { get; set; }
            public Cover cover { get; set; }
            public string publish_date { get; set; }
            public string key { get; set; }
            public List<Author> authors { get; set; }
        }

        public static Book getBookInfo(string isbn)
        {
            Book result = null;
            try
            {
                //build webrequest 
                string url = "https://openlibrary.org/api/books?bibkeys=ISBN:" + isbn + "&jscmd=data&format=json";

                HttpWebRequest req = WebRequest.Create(url)
                           as HttpWebRequest;


                using (HttpWebResponse resp = req.GetResponse()as HttpWebResponse)
                {
                    if (resp.StatusCode == HttpStatusCode.OK)
                    {
                        //read the json string
                        StreamReader reader =
                        new StreamReader(resp.GetResponseStream());
                        string json = reader.ReadToEnd();

                        if (json.Equals("{}"))
                        {
                            MessageBox.Show("Buch wurde nicht gefunden");
                        }
                        else
                        {

                            //remove unnecessary stuff
                            int start = json.IndexOf(": {");
                            json = json.Substring(start + 1, (json.LastIndexOf("}") - 1) - start);


                            //deserialize into new object of OpenLibraryBook 
                            JavaScriptSerializer jss = new JavaScriptSerializer();
                            OpenLibraryBook openLibraryInfo = jss.Deserialize<OpenLibraryBook>(json);

                            //create authors string
                            string authors = String.Empty;

                            if (openLibraryInfo.authors != null)
                            {
                                foreach (Author author in openLibraryInfo.authors)
                                {
                                    authors = authors + author.name + ", ";
                                }
                            }
                            else if (openLibraryInfo.publishers != null)
                            {
                                foreach (Publisher publisher in openLibraryInfo.publishers)
                                {
                                    authors = authors + publisher.name + ", ";
                                }
                            }

                            authors = authors.Remove(authors.LastIndexOf(","));

                            DateTime publishDate;
                            int year;

                            if (DateTime.TryParse(openLibraryInfo.publish_date, out publishDate))
                            {
                                year = publishDate.Year;
                            }
                            else
                            {
                                year = Int32.Parse(openLibraryInfo.publish_date);
                            }

                            if (isbn.Length == 13)
                            {
                                result = new Book(openLibraryInfo.title, authors, year, openLibraryInfo.identifiers.isbn_13[0]);
                            }
                            else
                            {
                                result = new Book(openLibraryInfo.title, authors, year, openLibraryInfo.identifiers.isbn_10[0]);
                            }                         
                        }

                    }
                    else
                    {
                        throw new Exception("HTTP Response not OK");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return result;
        }
    }
}